import mitmproxy.http
from mitmproxy import options
from mitmproxy import proxy
from mitmproxy.tools.dump import DumpMaster
import re

# 要注入到页面的js代码
inject = """
//连接websocket服务端
var ws = new WebSocket('ws://localhost:8000/ws');

//连接成功时执行
ws.onopen= function() {
    ws.send('browser started')
};

// 收到服务端消息时执行
ws.onmessage= function(evt) {
    // evt.data 是websocket服务端发送过来的值
    console.log(evt.data);

    //调用目标加密函数
    //signature = window.load_iqXQq;
    //console.log(signature);
     var signature = '带带弟弟'
    //将生成的值发送给websocket服务端
    ws.send(signature);
};


"""


# test = """var ws=new WebSocket('ws://localhost:8000/ws');ws.onopen=function(){var n={"url":"http://m.tujia.com/bingo/h5/house/gethouse/v3/bnb","data":{"houseParameter":{"houseId":11160752,"houseGuid":"","graft":false,"preview":false},"productParameter":{"activityInfo":"","checkInDate":"2021-04-09","checkOutDate":"2021-04-10","needPrice":true,"productId":"","bookingCount":1,"peopleCount":1}}};ws.send(JSON.stringify(e.iqXQq(t,n)));};window.load_iqXQq;window.load_iqXQq=e.iqXQq(t,n);"""
test = """var ws=new WebSocket('ws://localhost:8000/ws');ws.onopen=function(){ws.send('开始wss')};window.load_iqXQq;window.load_iqXQq=e.iqXQq;ws.onmessage=function(evt){console.log(evt.data);var signature=JSON.stringify(window.load_iqXQq(t,evt.data));var _cookie=document.cookie;ws.send(signature+'^'+_cookie)};"""
# test = """window.ws=new WebSocket('ws://localhost:8000/ws');window.ws.onopen=function(){ws.send('开始wss')};window.load_iqXQq;window.ws.postmessage=function(evt){window.load_iqXQq=e.iqXQq(t,evt.data);window.ws.send(JSON.stringify(window.load_iqXQq))};"""
test = """window.ws=new WebSocket('ws://127.0.0.1:10512/');window.ws.onopen=function(e){console.log("连接服务器成功");window.ws.send("Browser")}; """
class Myaddon():
    def response(self, flow):
        if 'chunk-vendors.950f610f' in flow.request.url:  # 注入到acrawler.js文件里
            print('ddddddf')
            chunk_vendors_js = flow.response.text
            index_list = [i.start() for i in re.finditer('e.iqXQq', chunk_vendors_js)][0]  # 选取出现加密函数位置索引
            new_chunk_vendors_js = chunk_vendors_js[:index_list-7] + test + chunk_vendors_js[index_list-7:]
            flow.response.text = new_chunk_vendors_js

addons = [
    Myaddon()
]


def run():
    myaddon = Myaddon()
    port = 8080
    opts = options.Options(listen_port=port)
    pconf = proxy.config.ProxyConfig(opts)
    m = DumpMaster(opts)
    m.server = proxy.server.ProxyServer(pconf)
    m.addons.add(myaddon)

    print(f'启动监听 {port} 端口')
    try:
        m.run()
    except KeyboardInterrupt:
        m.shutdown()


if __name__ == "__main__":
    run()
